<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useUserStore } from '@/store/userStore';
import { useRoute, useRouter } from 'vue-router';
import { useLocale } from 'vuetify';
import { login } from '@/api/user';
import { useSnackbarStore } from '@/store/snackbarStore';
import axios from '@/plugins/axios';
import Logo from '@/components/Logo.vue';

const { t } = useLocale();
const snackbarStore = useSnackbarStore();
const submiting = ref(false);
const isRegisterMode = ref(false);
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

// 登录表单验证
const loginFormValid = ref(false);
const registerFormValid = ref(false);

// 登录表单验证规则
const loginFormRules = reactive({
  studentId: [(v: string) => !!v || '请输入学号'],
  password: [(v: string) => !!v || '请输入密码'],
  role: [(v: string) => !!v || '请选择身份']
});

// 注册表单验证规则
const registerFormRules = reactive({
  studentId: [(v: string) => !!v || '请输入学号'],
  password: [(v: string) => !!v || '请输入密码'],
  name: [(v: string) => !!v || '请输入姓名'],
  phone: [(v: string) => !!v || '请输入电话号码'],
  gender: [(v: string) => !!v || '请选择性别'],
  role: [(v: string) => !!v || '请选择身份']
});

// 登录表单数据
const loginFormModel = reactive({
  studentId: '',
  password: '',
  role: ''
});

// 注册表单数据
const registerFormModel = reactive({
  studentId: '',
  password: '',
  name: '',
  phone: '',
  gender: '',
  role: ''
});

// 性别选项
const genderOptions = [
  { title: '男', value: 'M' },
  { title: '女', value: 'F' }
];

// 身份选项
const roleOptions = [
  { title: '学生', value: 'STUDENT' },
  { title: '初访员', value: 'INITIAL_VISITOR' },
  { title: '心理助理', value: 'ASSISTANT' },
  { title: '咨询师', value: 'CONSULTANT' },
  { title: '管理员', value: 'ADMIN' }
];

// 生成随机extra_info
const generateExtraInfo = () => {
  const departments = ['计算机学院', '电子工程学院', '机械学院', '化学学院', '数学学院'];
  const classes = ['1班', '2班', '3班', '4班', '5班'];
  const titles = ['助教', '讲师', '副教授', '教授'];
  const specialties = ['青少年心理', '学业压力', '情感问题', '人际关系', '职业规划'];
  
  let extraInfo = {};
  
  switch (registerFormModel.role) {
    case 'STUDENT':
      extraInfo = {
        department: departments[Math.floor(Math.random() * departments.length)],
        student_id: registerFormModel.studentId,
        class: classes[Math.floor(Math.random() * classes.length)]
      };
      break;
    case 'INITIAL_VISITOR':
    case 'CONSULTANT':
      extraInfo = {
        title: titles[Math.floor(Math.random() * titles.length)],
        specialty: specialties[Math.floor(Math.random() * specialties.length)]
      };
      break;
    case 'ASSISTANT':
      extraInfo = {
        title: '心理咨询助理',
        responsibility: '预约管理'
      };
      break;
    case 'ADMIN':
      extraInfo = {
        title: '心理咨询中心管理员'
      };
      break;
  }
  
  return JSON.stringify(extraInfo);
};

// 登录处理
const handleLogin = async () => {
  if (loginFormValid.value) {
    submiting.value = true;
    try {
      // 使用学号、密码和身份进行登录
      const loginData = {
        username: loginFormModel.studentId,
        password: loginFormModel.password,
        role: loginFormModel.role
      };
      
      console.log('登录数据:', loginData);
      
      // 直接调用后端登录API
      const response = await axios.post('/api/user/login.do', loginData);
      
      if (response.data.success) {
        // 模拟登录成功，设置token
        userStore.setToken('mock-token-' + Date.now());
        
        // 保存完整的用户信息
        const userData = response.data.data;
        userStore.setUserInfo(userData);
        
        // 设置用户名（用于兼容性）
        userStore.setUsername(userData.username);
        
        snackbarStore.showMessage(`登录成功！欢迎 ${userData.name}（${userStore.getRoleText}）`);
        router.replace(route.query.to ? String(route.query.to) : '/main');
      } else {
        // 根据不同的错误码提供更具体的错误信息
        let errorMessage = '登录失败，请检查学号、密码和身份';
        if (response.data.code === 401) {
          errorMessage = '用户名或密码错误';
        } else if (response.data.code === 403) {
          errorMessage = '账号已被禁用，请联系管理员';
        } else if (response.data.code === 400) {
          errorMessage = response.data.message || '身份不匹配，请选择正确的身份';
        } else if (response.data.message) {
          errorMessage = response.data.message;
        }
        snackbarStore.showMessage(errorMessage);
      }
    } catch (error) {
      console.error('登录失败:', error);
      snackbarStore.showMessage('登录失败，请检查网络连接或联系管理员');
    } finally {
      submiting.value = false;
    }
  }
};

// 注册处理
const handleRegister = async () => {
  if (registerFormValid.value) {
    submiting.value = true;
    try {
      // 准备注册数据
      const registerData = {
        username: registerFormModel.studentId,
        password: registerFormModel.password,
        name: registerFormModel.name,
        phone: registerFormModel.phone,
        gender: registerFormModel.gender,
        role: registerFormModel.role,
        extra_info: generateExtraInfo(),
        is_active: true
      };

      console.log('注册数据:', registerData);

      // 调用后端API
      const response = await axios.post('/api/user/add.do', registerData);
      
      if (response.data.success) {
        snackbarStore.showMessage('注册成功！请使用学号、密码和身份登录');
        // 清空表单
        Object.keys(registerFormModel).forEach(key => {
          registerFormModel[key] = '';
        });
        // 切换到登录模式
        isRegisterMode.value = false;
      } else {
        snackbarStore.showMessage(response.data.message || '注册失败，请重试');
      }
    } catch (error) {
      console.error('注册失败:', error);
      snackbarStore.showMessage('注册失败，请检查网络连接或联系管理员');
    } finally {
      submiting.value = false;
    }
  }
};
</script>

<template>
  <div class="auth">
    <div class="auth-wrapper">
      <VCard rounded="md" elevation="10" class="login-card" max-width="500">
        <VCardItem class="pa-sm-8">
          <div class="d-flex flex-column align-center justify-center py-4">
            <Logo :height="32" />
          </div>
          <div class="text-body-1 text-muted text-center mb-3">心理咨询系统</div>
          
          <!-- 模式切换按钮 -->
          <div class="d-flex justify-center mb-4">
            <VTabs v-model="isRegisterMode" color="primary" class="w-100">
              <VTab :value="false" class="flex-1">
                <VIcon icon="mdi-login" class="mr-2" />
                登录
              </VTab>
              <VTab :value="true" class="flex-1">
                <VIcon icon="mdi-account-plus" class="mr-2" />
                注册
              </VTab>
            </VTabs>
          </div>

          <!-- 登录表单 -->
          <VForm v-if="!isRegisterMode" v-model="loginFormValid" @submit.prevent>
            <VRow class="d-flex mb-3">
              <VCol cols="12">
                <VLabel class="mb-1">学号</VLabel>
                <VTextField 
                  variant="outlined" 
                  color="primary"
                  :rules="loginFormRules.studentId"
                  v-model="loginFormModel.studentId"
                  placeholder="请输入学号"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">密码</VLabel>
                <VTextField 
                  variant="outlined" 
                  type="password" 
                  color="primary"
                  :rules="loginFormRules.password"
                  v-model="loginFormModel.password"
                  placeholder="请输入密码"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">身份</VLabel>
                <VSelect
                  variant="outlined"
                  color="primary"
                  :items="roleOptions"
                  item-title="title"
                  item-value="value"
                  :rules="loginFormRules.role"
                  v-model="loginFormModel.role"
                  placeholder="请选择身份"
                />
              </VCol>
              
              <VCol cols="12" class="pt-0">
                <VBtn 
                  :loading="submiting"
                  type="submit"
                  color="primary" 
                  block 
                  flat
                  @click="handleLogin"
                >
                  登录
                </VBtn>
              </VCol>
            </VRow>
          </VForm>

          <!-- 注册表单 -->
          <VForm v-else v-model="registerFormValid" @submit.prevent>
            <VRow class="d-flex mb-3">
              <VCol cols="12">
                <VLabel class="mb-1">学号 *</VLabel>
                <VTextField 
                  variant="outlined" 
                  color="primary"
                  :rules="registerFormRules.studentId"
                  v-model="registerFormModel.studentId"
                  placeholder="请输入学号"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">密码 *</VLabel>
                <VTextField 
                  variant="outlined" 
                  type="password" 
                  color="primary"
                  :rules="registerFormRules.password"
                  v-model="registerFormModel.password"
                  placeholder="请输入密码"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">姓名 *</VLabel>
                <VTextField 
                  variant="outlined" 
                  color="primary"
                  :rules="registerFormRules.name"
                  v-model="registerFormModel.name"
                  placeholder="请输入姓名"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">电话号码 *</VLabel>
                <VTextField 
                  variant="outlined" 
                  color="primary"
                  :rules="registerFormRules.phone"
                  v-model="registerFormModel.phone"
                  placeholder="请输入手机号码"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">性别 *</VLabel>
                <VSelect
                  variant="outlined"
                  color="primary"
                  :items="genderOptions"
                  item-title="title"
                  item-value="value"
                  :rules="registerFormRules.gender"
                  v-model="registerFormModel.gender"
                  placeholder="请选择性别"
                />
              </VCol>
              
              <VCol cols="12">
                <VLabel class="mb-1">身份 *</VLabel>
                <VSelect
                  variant="outlined"
                  color="primary"
                  :items="roleOptions"
                  item-title="title"
                  item-value="value"
                  :rules="registerFormRules.role"
                  v-model="registerFormModel.role"
                  placeholder="请选择身份"
                />
              </VCol>
              
              <VCol cols="12" class="pt-0">
                <VBtn 
                  :loading="submiting"
                  type="submit"
                  color="primary" 
                  block 
                  flat
                  @click="handleRegister"
                >
                  注册
                </VBtn>
              </VCol>
            </VRow>
          </VForm>
        </VCardItem>
      </VCard>
    </div>
  </div>
</template>

<style lang="scss">
.login-card {
  overflow: visible;
  &::before {
    content: '';
    background: url(/assets/svg/dot2.svg);
    width: 6rem;
    height: 6rem;
    position: absolute;
    bottom: -2rem;
    left: -2rem;
    z-index: 0;
  }
}
</style>
